package com.walming.generator.copycat.annotaion.processor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.walming.generator.copycat.annotaion.ConditionProcessor;
import com.walming.generator.copycat.annotaion.Time;
import com.walming.generator.copycat.annotaion.Timestamp;
import com.walming.generator.copycat.enums.CompareEnum;
import com.walming.generator.copycat.enums.TimeQueryFormat;
import com.walming.generator.copycat.extend.AbstractQuery;
import com.walming.generator.copycat.utils.TimeUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * {@link Timestamp} 注解处理器
 *
 * @param <QUERY>  自定义查询 Query
 * @param <ENTITY> 查询想对应的实体类型
 * @author walming
 * @date 2020-05-12 22:44
 */
@ConditionProcessor(targetAnnotation = Time.class)
public class TimeProcessor<QUERY extends AbstractQuery, ENTITY>
        extends CriteriaAnnotationProcessorAdaptor<Time, QUERY, QueryWrapper<ENTITY>, ENTITY> {

    @Override
    public boolean process(QueryWrapper<ENTITY> queryWrapper, Field field, QUERY query, Time criteriaAnnotation) {

        final Object value = this.columnValue(field, query);
        if (this.isNullOrEmpty(value) || !(value instanceof Date)) {
            // 属性值为 Null OR Empty 跳过
            return true;
        }
        String columnName = criteriaAnnotation.alias();
        if (StringUtils.isEmpty(columnName)) {
            columnName = this.columnName(field, criteriaAnnotation.naming());
        }
        assert columnName != null;
        CompareEnum compare = criteriaAnnotation.compare();
        TimeQueryFormat format = criteriaAnnotation.format();

        switch (compare) {
            case EQ:
                queryWrapper.eq(columnName, TimeUtils.format((Date) value, format));
                break;
            case NE:
                queryWrapper.ne(columnName, TimeUtils.format((Date) value, format));
                break;
            case GE:
                queryWrapper.ge(columnName, TimeUtils.format((Date) value, format));
                break;
            case GT:
                queryWrapper.gt(columnName, TimeUtils.format((Date) value, format));
                break;
            case LE:
                queryWrapper.le(columnName, TimeUtils.format((Date) value, format));
                break;
            default:
                queryWrapper.lt(columnName, TimeUtils.format((Date) value, format));
                break;
        }

        return true;
    }

}
